package com.xj.admin.bussiness.device.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.xj.common.base.common.bean.AbstractBean;
import com.xj.common.bussiness.device.entity.TbDevice;
import org.springframework.stereotype.Controller;
import com.xj.admin.base.index.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.plugins.Page;
import com.feilong.core.Validator;
import com.xj.admin.bussiness.device.service.ITbDeviceService;
import com.xj.admin.util.JsonUtil;
import com.xj.admin.util.dtgrid.model.Pager;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Hmemb
 * @since 2018-04-08
 */
@Controller
@RequestMapping("/device/")
public class TbDeviceController extends BaseController {

    @Autowired
    private ITbDeviceService deviceService;

    @GetMapping("listUI")
    public String listUI() {
        return "device/list";
    }

    @GetMapping("form")
    public String form(Map<String, Object> map) {
        return "device/form";
    }

    @PostMapping("list")
    @ResponseBody
    public Object list(String gridPager) {
        Pager pager = JsonUtil.getObjectFromJson(gridPager, Pager.class);
        Map<String, Object> parameters = null;
        if (Validator.isNullOrEmpty(pager.getParameters())) {
            parameters = new HashMap<>();
        } else {
            parameters = pager.getParameters();
        }
        Page<TbDevice> list = deviceService.selectPage(new Page<TbDevice>(pager.getNowPage(), pager.getPageSize()), Condition.create().allEq(parameters));
        makeGridResult(parameters, pager, list);
        return parameters;
    }

    @PostMapping("save")
    @ResponseBody
    public AbstractBean add(TbDevice tbdevice) {
        if (tbdevice.getId() == null) {
            tbdevice.setUpdateTime(new Date());
            tbdevice.setInsertTime(new Date());
        }
        if (!deviceService.insertOrUpdate(tbdevice)) {
            return error();
        }
        return success();
    }

    @DeleteMapping("{id}/delete")
    @ResponseBody
    public AbstractBean delete(@PathVariable(required = true) Integer id) {
        if (!deviceService.deleteById(id)) {
            return error();
        }
        return success();
    }

    @GetMapping("{id}/select")
    public String select(Map<String, Object> map, @PathVariable(required = true) Integer id) {
        TbDevice tbdevice = deviceService.selectById(id);
        map.put("record", tbdevice);
        return "device/edit";
    }
}
